package de.koller.worlders.render.util;

import de.koller.oceanFramework.glyph.GlyphRendererGL;
import de.koller.oceanFramework.glyph.GlyphScreen;
import de.koller.oceanFramework.glyph.GlyphScreenGL;
import de.koller.oceanFramework.tree.Child;
import de.koller.worlders.WSea;
import de.koller.worlders.WorldersRoot;
import de.koller.worlders.gameplay.resource.FontValue;

public class SpeechBubble extends WSea {
	
	@Child private final GlyphScreenGL gscreen;

	public SpeechBubble( int maxSize ) {
		gscreen = new GlyphScreenGL( maxSize, maxSize,
			new FontValue(), "de/koller/worlders/gameplay/resource/font.png" );
		gscreen.setAutomaticBuffering( false );
	}
	
	public void render( String[] lines, float x, float y ) {
		GlyphRendererGL r = gscreen.getRenderer();
		int w = 0;
		for( String s : lines )
			w = Math.max( w, s.length() );
		w += 1;
		int h = lines.length + 1;
		
		//Border
		r.setCurrentBackColor( 0x00000000 );
		r.setCurrentFontColor( 0xff000000 );
		r.setCurrentSecColor(  0xffffffff );
		
		r.renderGlyph( 0, 0, 5, 7 );
		for( int i = 1; i <= h-1; i++ )
			r.renderGlyph( 0, i, 8, 8 );
		r.renderGlyph( 0, h, 5, 8 );
		for( int i = 1; i <= w-1; i++ )
			r.renderGlyph( i, h, 7, 8 );
		r.renderGlyph( w, h, 6, 8 );
		for( int i = 1; i <= h-1; i++ )
			r.renderGlyph( w, i, 9, 8 );
		r.renderGlyph( w, 0, 6, 7 );
		for( int i = 1; i <= w-1; i++ )	
			r.renderGlyph( i, 0, 7, 7 );
		
		r.setCurrentBackColor( 0xffffffff );
		r.setCurrentFontColor( 0xff000000 );
		for( int gx = 1; gx <= w-1; gx++ )
			for( int gy = 1; gy <= h-1; gy++ )
				r.renderString( gx, gy, " " );
		
		for( int i = 0; i < lines.length; i++ )
			r.renderString( 1, i+1, lines[i] );
		
		float sbw = (w+1) * GlyphScreen.GLYPH_WIDTH;
		float sbh = (h+1)*GlyphScreen.GLYPH_HEIGHT;
		float sx = x - sbw / 2;
		if( sx < 0 ) sx = 0;
		if( sx + sbw > WorldersRoot.D_WIDTH ) sx = WorldersRoot.D_WIDTH - sbw;
		float sy = y - sbh;
		if( sy < 0 ) sy = 0;
		if( sy + sbh > WorldersRoot.D_HEIGHT ) sy = WorldersRoot.D_HEIGHT - sbh;
		
		gscreen.updateBuffer();
		gscreen.getTexture().draw2D( sx, sy, 
				gscreen.getTexture().getSize(), gscreen.getTexture().getSize(), 21 );
	}
	
}
